package com.example.icongyou;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.icongyou.R;
import com.example.icongyou.api.TeamAssignmentApi;
import com.example.icongyou.bean.TeamAssignment;
import com.example.icongyou.retrofit.RetrofitClient;

import java.math.BigDecimal;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AssignmentCheckActivity extends AppCompatActivity {

    private TextView tvStudentName, tvStudentId, tvSubmitTime, tvContent;
    private EditText etCompletion, etCodeQuality, etReportQuality, etInnovation, etComment;
    private TextView tvTotalScore;
    private Button btnTeacherRecommend, btnSubmit;

    private TeamAssignmentApi teamAssignmentApi;
    private TeamAssignment currentAssignment;
    private Long assignmentId;
    private String teamName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_assigment_check); // 您的评分页布局

        initViews();
        initApi();
        getIntentData();
        loadAssignmentData();
        setupListeners();
    }

    private void initViews() {
        // 学生信息区域
        tvStudentName = findViewById(R.id.tv_student_name);
        tvStudentId = findViewById(R.id.tv_student_id);
        tvSubmitTime = findViewById(R.id.tv_submit_time);
        tvContent = findViewById(R.id.tv_content);

        // 评分输入区域
        etCompletion = findViewById(R.id.et_completion);
        etCodeQuality = findViewById(R.id.et_code_quality);
        etReportQuality = findViewById(R.id.et_report_quality);
        etInnovation = findViewById(R.id.et_innovation);
        etComment = findViewById(R.id.et_comment);

        // 总分和按钮
        tvTotalScore = findViewById(R.id.tv_total_score);
        btnTeacherRecommend = findViewById(R.id.btn_teacher_recommend);
        btnSubmit = findViewById(R.id.btn_submit);
    }

    private void initApi() {
        teamAssignmentApi = RetrofitClient.getTeamAssignmentApi();
    }

    private void getIntentData() {
        // 从作业列表页获取传递的数据
        Intent intent = getIntent();
        assignmentId = intent.getLongExtra("assignmentId", -1L);
        teamName = intent.getStringExtra("teamName");
        double currentScore = intent.getDoubleExtra("currentScore", 0.0);

        if (assignmentId == -1L) {
            Toast.makeText(this, "作业数据错误", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 如果已有分数，显示在总分区域
        if (currentScore > 0) {
            tvTotalScore.setText(String.valueOf(currentScore));
        }
    }

    private void loadAssignmentData() {
        // 根据ID获取团队作业详情
        Call<TeamAssignment> call = teamAssignmentApi.getTeamAssignment(assignmentId);
        call.enqueue(new Callback<TeamAssignment>() {
            @Override
            public void onResponse(Call<TeamAssignment> call, Response<TeamAssignment> response) {
                if (response.isSuccessful() && response.body() != null) {
                    currentAssignment = response.body();
                    updateUI();
                } else {
                    Toast.makeText(AssignmentCheckActivity.this, "加载作业失败", Toast.LENGTH_SHORT).show();
                    // 使用默认数据展示
                    showDefaultData();
                }
            }

            @Override
            public void onFailure(Call<TeamAssignment> call, Throwable t) {
                Toast.makeText(AssignmentCheckActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                // 使用默认数据展示
                showDefaultData();
            }
        });
    }

    private void updateUI() {
        if (currentAssignment != null) {
            // 更新学生信息
            tvStudentName.setText(teamName != null ? teamName : "第" + currentAssignment.getTeamId() + "组");
            tvStudentId.setText("学号：" + (currentAssignment.getSubmittedBy() != null ?
                    currentAssignment.getSubmittedBy().toString() : "未知"));

            // 更新提交时间
            if (currentAssignment.getSubmittedAt() != null) {
                tvSubmitTime.setText(formatDateTime(currentAssignment.getSubmittedAt().toString()));
            } else {
                tvSubmitTime.setText("未提交");
            }

            // 更新提交内容（这里使用作业文件信息作为内容）
            String content = currentAssignment.getAssignmentFile() != null ?
                    "已提交文件: " + currentAssignment.getAssignmentFile() :
                    "本次作业我完成了所有要求的实验内容。\n\n实验过程中遇到的主要问题是...\n\n通过查阅资料解决了这些问题。";
            tvContent.setText(content);

            // 如果已有评分，显示评分数据
            if (currentAssignment.getScore() != null &&
                    currentAssignment.getScore().compareTo(BigDecimal.ZERO) > 0) {
                displayExistingScores();
            }

            // 更新教师推荐按钮状态
            updateTeacherRecommendButton();
        }
    }

    private void showDefaultData() {
        // 使用传递的数据显示默认信息
        tvStudentName.setText(teamName != null ? teamName : "未知团队");
        tvStudentId.setText("学号：未知");
        tvSubmitTime.setText("未知时间");
        tvContent.setText("本次作业我完成了所有要求的实验内容。\n\n实验过程中遇到的主要问题是...\n\n通过查阅资料解决了这些问题。");
    }

    private void displayExistingScores() {
        if (currentAssignment != null && currentAssignment.getScore() != null) {
            BigDecimal totalScore = currentAssignment.getScore();
            tvTotalScore.setText(totalScore.toString());

            // 这里可以根据您的业务逻辑将总分分解到各个评分项
            // 例如：假设总分是各个分项的和，这里可以设置默认值
            // 您可能需要根据实际业务调整这个逻辑
            etCompletion.setText("25");
            etCodeQuality.setText("20");
            etReportQuality.setText("15");
            etInnovation.setText("10");
        }
    }

    private void updateTeacherRecommendButton() {
        if (currentAssignment != null && currentAssignment.isExcellent()) {
            btnTeacherRecommend.setText("已推荐");
            btnTeacherRecommend.setEnabled(false);
            btnTeacherRecommend.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
        }
    }

    private void setupListeners() {
        // 分数输入监听，实时计算总分
        setupScoreListeners();

        // 教师推荐按钮
        btnTeacherRecommend.setOnClickListener(v -> markAsExcellent());

        // 提交评分按钮
        btnSubmit.setOnClickListener(v -> submitGrading());
    }

    private void setupScoreListeners() {
        TextWatcher scoreWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                calculateTotalScore();
            }
        };

        etCompletion.addTextChangedListener(scoreWatcher);
        etCodeQuality.addTextChangedListener(scoreWatcher);
        etReportQuality.addTextChangedListener(scoreWatcher);
        etInnovation.addTextChangedListener(scoreWatcher);
    }

    private void calculateTotalScore() {
        try {
            int completion = getScoreFromEditText(etCompletion);
            int codeQuality = getScoreFromEditText(etCodeQuality);
            int reportQuality = getScoreFromEditText(etReportQuality);
            int innovation = getScoreFromEditText(etInnovation);

            int total = completion + codeQuality + reportQuality + innovation;
            tvTotalScore.setText(String.valueOf(total));
        } catch (NumberFormatException e) {
            tvTotalScore.setText("0");
        }
    }

    private int getScoreFromEditText(EditText editText) {
        String text = editText.getText().toString().trim();
        if (text.isEmpty()) {
            return 0;
        }
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    private void markAsExcellent() {
        // 标记为优秀作业
        BigDecimal totalScore = getTotalScore();
        Call<Void> call = teamAssignmentApi.updateScore(assignmentId, totalScore, 1); // 1表示优秀

        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(AssignmentCheckActivity.this, "已标记为优秀作业", Toast.LENGTH_SHORT).show();
                    btnTeacherRecommend.setText("已推荐");
                    btnTeacherRecommend.setEnabled(false);
                    btnTeacherRecommend.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));

                    // 更新本地数据
                    if (currentAssignment != null) {
                        currentAssignment.markAsExcellent();
                    }
                } else {
                    Toast.makeText(AssignmentCheckActivity.this, "标记失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Toast.makeText(AssignmentCheckActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void submitGrading() {
        BigDecimal totalScore = getTotalScore();
        String comment = etComment.getText().toString().trim();

        if (totalScore.compareTo(BigDecimal.ZERO) == 0) {
            Toast.makeText(this, "请输入评分", Toast.LENGTH_SHORT).show();
            return;
        }

        // 更新分数（0表示非优秀，如果要点推荐需要单独点击教师推荐按钮）
        Call<Void> call = teamAssignmentApi.updateScore(assignmentId, totalScore, 0);

        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(AssignmentCheckActivity.this, "评分提交成功", Toast.LENGTH_SHORT).show();

                    // 设置返回结果，让列表页刷新
                    Intent resultIntent = new Intent();
                    setResult(RESULT_OK, resultIntent);
                    finish(); // 返回上一页
                } else {
                    Toast.makeText(AssignmentCheckActivity.this, "评分提交失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Toast.makeText(AssignmentCheckActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private BigDecimal getTotalScore() {
        try {
            String totalScoreStr = tvTotalScore.getText().toString();
            return new BigDecimal(totalScoreStr);
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO;
        }
    }

    private String formatDateTime(String dateTime) {
        // 简化处理，实际中您可能需要更复杂的日期格式化
        if (dateTime == null) return "未知时间";
        try {
            // 假设日期格式为 "2023-05-15T14:30:00"
            return dateTime.replace("T", " ").substring(0, 16);
        } catch (Exception e) {
            return dateTime;
        }
    }

    @Override
    public void onBackPressed() {
        // 返回时设置结果，让列表页知道需要刷新
        setResult(RESULT_CANCELED);
        super.onBackPressed();
    }
}